package com.chrisgammage.gtwit.server;

import com.chrisgammage.gtwit.client.GTwitService;
import com.chrisgammage.gtwit.client.Tweet;
import com.google.gson.Gson;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by IntelliJ IDEA.
 * User: gammagec
 * Date: 5/31/12
 * Time: 12:22 AM
 */
public class GTwitServiceImpl extends RemoteServiceServlet implements GTwitService {

    static CacheManager cacheManager = CacheManager.getInstance();

    static {
        cacheManager = CacheManager.create();
        Cache cache = new Cache("tweetsCache", 50, false, false, 120, 120);

        cacheManager.addCache(cache);
    }

    public Tweet[] getTweets(String userId, int count) {
        Ehcache cache = cacheManager.getCache("tweetsCache");
        String key = userId + " " + count;
        Element tweetsElement = cache.get(key);
        if (tweetsElement == null) {
            Tweet[] tweets = getTweetResults(userId, count);
            cache.put(new Element(key, tweets));
            return tweets;
        }
        return (Tweet[])tweetsElement.getObjectValue();
    }

    private Tweet[] getTweetResults(String userId, int count) {
        StringBuilder urlStr = new StringBuilder();
        urlStr.append("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true");
        urlStr.append("&screen_name=").append(userId);
        urlStr.append("&count=").append(count);
        try {
            URL url = new URL(urlStr.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setReadTimeout(10000);
            conn.connect();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line + '\n');
            }
            System.out.println(sb.toString());

            Gson gson = new Gson();
            Tweet[] tweets = gson.fromJson(sb.toString(), Tweet[].class);
            return tweets;
        } catch (Exception e) {
            return null;
        }
    }
}